package org.elephas.service;

import java.util.List;

import org.elephas.model.Post;
import org.elephas.persistence.Dao;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PostFinder {

	@Autowired
	private Dao dao;

	/**
	 * Loads the post with the specified id.
	 * 
	 * @param uuiid
	 *            the post's id
	 * @return the post with the specified id.
	 * @throws PostNotFoundException
	 */
	public Post findById(String uuiid) {
		Post post = (Post) dao.get(Post.class, uuiid);
		if (post == null) {
			throw new PostNotFoundException(uuiid);
		}
		return post;
	}

	public List<Post> loadRecentPosts(int nrOfPosts) {
		StringBuffer sb = new StringBuffer();
		sb.append("from Post post");
		sb.append(" order by post.created desc");

		Query query = dao.createQuery(sb.toString());

		query.setMaxResults(nrOfPosts);

		return query.list();
	}
}
